package net.sinmetal.twitcockpit.controller.cockpit.schedule;

import net.sinmetal.twitcockpit.form.cockpit.schedule.AutoPostForm;
import net.sinmetal.twitcockpit.service.AutoPostService;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.util.RequestMap;

/**
 * CockpitScheduleEntryController
 *
 * @author Sinmetal
 *
 */
public class EntryController extends Controller {

    private AutoPostService service = new AutoPostService();

    /**
     * 定期Post登録
     */
    @Override
    public Navigation run() throws Exception {
        final String TOP_PAGE = "/";
        RequestMap map = new RequestMap(request);
        if (!validate(map)) {
            return forward(TOP_PAGE);
        }
        AutoPostForm form = AutoPostForm.getInstance(map);
        service.put(form);
        return redirect(TOP_PAGE);
    }

    /**
     * validate
     *
     * @param requestMap
     * @return
     */
    private boolean validate(RequestMap requestMap) {
        Validators v = new Validators(requestMap);
        v.add("tweet", v.required(), v.maxlength(140));
        v.add("startmonth", v.required(), v.integerType(), v.longRange(1, 12));
        v.add("startday", v.required(), v.integerType(), v.longRange(1, 31));
        v.add("starthour", v.required(), v.integerType(), v.longRange(0, 23));
        v.add("startminute", v.required(), v.integerType());
        v.add("endmonth", v.required(), v.integerType(), v.longRange(1, 12));
        v.add("endday", v.required(), v.integerType(), v.longRange(1, 31));
        v.add("endhour", v.required(), v.integerType(), v.longRange(0, 23));
        v.add("endminute", v.required(), v.integerType());
        return v.validate();
    }
}
